package com.wingsboat.file.config;

import com.wingsboat.common.core.enums.FileServerTypeEnum;
import com.wingsboat.file.service.FastDfsSysFileServiceImpl;
import com.wingsboat.file.service.LocalSysFileServiceImpl;
import com.wingsboat.file.service.MinioSysFileServiceImpl;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;


@Configuration
class WingsBoatConfiguration {
    @Bean
    public WingsBoatBeanDefinitionRegistrar wingLinksBeanDefinitionRegistrar() {
        return new WingsBoatBeanDefinitionRegistrar();
    }
}

/**
 * @author wangzhong
 * @description: 导入式动态bean注入
 * @date 2024/5/24 13:40
 */
public class WingsBoatBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {
    private Environment environment;


    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
        Class<?> beanClass = getFileServerClass();
        String beanName = beanClass.getSimpleName();
        registerBeanDefinition(registry, beanClass, beanName);
    }

    /**
     * get active file server class
     * @return .class
     */
    private Class<?> getFileServerClass() {
        boolean selectorFastDfs = Boolean.parseBoolean(environment.getProperty(FileServerSelector.selectorFileServerKey, FileServerTypeEnum.FAST_DFS.getCode()));
        boolean selectorMinio = Boolean.parseBoolean(environment.getProperty(FileServerSelector.selectorFileServerKey, FileServerTypeEnum.MINIO.getCode()));
        return selectorFastDfs ? FastDfsSysFileServiceImpl.class
                : selectorMinio ? MinioSysFileServiceImpl.class
                : LocalSysFileServiceImpl.class;
    }

    /**
     * 注入bean
     * @param registry factory
     * @param beanClass bean class
     * @param beanName bean name
     */
    private void registerBeanDefinition(BeanDefinitionRegistry registry, Class<?> beanClass, String beanName) {
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(beanClass).getBeanDefinition();
        registry.registerBeanDefinition(beanName, beanDefinition);
    }



    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}
